<template>
    <v-container fluid class="textarea-container">
        <v-snackbar v-model="snackbar" :timeout="timeout" :color="color" :style="{ bottom: `90%` }">
            {{ message }}
        </v-snackbar>
        <v-select label="格式化类型" :items="['Cookie', 'Header', 'JSon']" v-model="selectedValue"
            @update:model-value="handleChange"></v-select>
        <v-row class="row" style="height: calc(90vh - 5%)">
            <v-col cols="6" class="col">
                <v-textarea label="请输入字符串格式或者列表格式" class="full-height" rows="23" v-model="inputValue"
                    @input="updateFormattedValue"></v-textarea>
            </v-col>

            <v-col cols="6" class="col" style="overflow-y: auto">
                <v-btn class="copy-button" @click="copyToClipboard">复制 JSON</v-btn>
                <v-btn class="copy-button" @click="copyToCStr">复制 字符串</v-btn>
                <v-btn class="copy-button" @click="copyToCys">压缩</v-btn>
                <json-viewer :value="jsonData" copyable boxed></json-viewer>
            </v-col>
        </v-row>
    </v-container>
</template>
  
<script>
import { ref } from "vue";
import { trimStart } from "lodash";
export default {
    setup() {
        const inputValue = ref("");
        const jsonData = ref({
            test: "Holle World!",
        });
        const selectedValue = ref("Cookie");
        const snackbar = ref(false); // 定义 snackbar 为响应式对象
        const message = ref(""); // 消息内容
        const timeout = ref(3000); // 弹出消息持续时间（以毫秒为单位）
        const color = ref("success"); // 弹出消息的颜色

        const copyToClipboard = () => {
            const fakeTextArea = document.createElement("textarea");
            fakeTextArea.value = JSON.stringify(jsonData.value);
            const cookieString = Object.entries(jsonData.value)
                .map(([key, value]) => `${key}=${value}`)
                .join("; ");
            console.log(cookieString);
            document.body.appendChild(fakeTextArea);
            fakeTextArea.select();
            document.execCommand("copy");
            document.body.removeChild(fakeTextArea);
            showSnackbar("已复制到剪贴板");
        };
        const copyToCStr = () => {
            const fakeTextArea = document.createElement("textarea");
            const cookieString = Object.entries(jsonData.value)
                .map(([key, value]) => `${key}=${value}`)
                .join("; ");
            fakeTextArea.value = cookieString;
            document.body.appendChild(fakeTextArea);
            fakeTextArea.select();
            document.execCommand("copy");
            document.body.removeChild(fakeTextArea);
            showSnackbar("已复制到剪贴板");
        };
        const copyToCys = () => {
            const fakeTextArea = document.createElement("textarea");
            fakeTextArea.value = JSON.stringify(jsonData.value);
            document.body.appendChild(fakeTextArea);
            fakeTextArea.select();
            document.execCommand("copy");
            document.body.removeChild(fakeTextArea);
            showSnackbar("已复制到剪贴板");
        };

        const updateFormattedValue = () => {
            const selectetype = selectedValue.value;
            const formattedValue = {};
            if (selectetype === "Cookie") {
                try {
                    try {
                        const cookieArray = JSON.parse(inputValue.value);
                        if (Array.isArray(cookieArray)) {
                            cookieArray.forEach((cookie) => {
                                formattedValue[cookie.name] = cookie.value;
                            });
                            jsonData.value = formattedValue;
                        } else {
                            console.error("输入的内容不是一个有效的数组");
                        }
                    } catch (error) {
                        inputValue.value.split(";").forEach((item) => {
                            const [key, value] = item.trim().split("=");
                            formattedValue[key] = value;
                        });
                        jsonData.value = formattedValue;
                    }
                } catch (error) {
                    console.error("无法解析输入的 JSON 字符串", error);
                }
            }
            if (selectetype === "Header") {
                const inputdata = inputValue.value
                    .replaceAll(":\n", ":")
                    .replaceAll("：\n", ":");
                console.log(inputdata);
                inputdata.split("\n").forEach((item) => {
                    const [key, value] = item.replace(":", "&&&").split("&&&");
                    formattedValue[key] = trimStart(value);
                });
                jsonData.value = formattedValue;
            }
            if (selectetype === "JSon") {
                try {
                    const inputdata = JSON.parse(inputValue.value);
                    jsonData.value = inputdata;
                } catch (e) {
                    console.log(e);
                    jsonData.value = "";
                }
            }
            console.log(jsonData.value);
        };

        const handleChange = () => {
            updateFormattedValue();
        };

        const showSnackbar = (messageContent) => {
            message.value = messageContent; // 设置要显示的消息内容
            snackbar.value = true; // 显示消息弹出
        };

        return {
            jsonData,
            updateFormattedValue,
            inputValue,
            selectedValue,
            copyToClipboard,
            copyToCStr,
            copyToCys,
            handleChange,
            snackbar, // 将 snackbar 添加到返回的对象中
            message, // 将 message 添加到返回的对象中
            timeout, // 将 timeout 添加到返回的对象中
            color, // 将 color 添加到返回的对象中
        };
    },
};
</script>
  
<style>
.textarea-container {
    height: 100vh;
}

.row {
    height: 100%;
}

.col {
    height: 100%;
}

.full-height {
    height: 100%;
}
</style>
  